package org.example.Tool.Component;

import javax.swing.*;
import java.awt.*;

public class AdjustIconBuilder {

    protected boolean isConstrained = false;

    protected Dimension size;

    protected Image image;

    protected Component parent;

    public void setFilename(String filename) {
        this.image = Toolkit.getDefaultToolkit().getImage(filename);
    }

    public void setConstrained(boolean constrained) {
        isConstrained = constrained;
    }

    public void setImage(Image image) {
        this.image = image;
    }

    public void setSize(Dimension size) {
        this.size = size;
    }

    public void setComponent(Component component){
        parent = component;
    }

    public ImageIcon of(){
        ImageIcon icon = new ImageIcon(){
            @Override
            public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
                Dimension iconSize;
                Point StartPoint = new Point(0,0);
                if(parent != null)
                    size = parent.getSize();
                if(isConstrained){
                    double ratio = Math.min(
                            1.0 * size.width / this.getIconWidth(),
                            1.0 * size.height / this.getIconHeight()
                    );
                    iconSize = new Dimension (
                            (int)(this.getIconWidth() * ratio),
                            (int)(this.getIconHeight() * ratio)
                    );
                    StartPoint.setLocation(
                            (size.height - iconSize.height) / 2,
                            (size.width - iconSize.width) / 2
                    );
                }
                else
                    iconSize = size;
                if(this.getImageObserver() != null)
                    throw new RuntimeException(this + ":null of ImageObserver");
                g.drawImage(this.getImage(),
                        StartPoint.x,StartPoint.y,
                        iconSize.width,iconSize.height,
                        getImageObserver()
                );
            }
        };
        if(image == null)
            throw new RuntimeException(this + ":img hasn't been set");
        icon.setImage(image);
        return icon;
    }
}
